package com.hanlink.dsp.ui.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.edge.pbx.view.PbxCircleSeekBar;
import com.edge.pbx.view.PbxImageButtonRadioLayout;
import com.edge.pbx.view.summing.PbxOutputSelectChannelView;
import com.edge.pbx.view.summing.PbxOutputSelectChannelsLayout;
import com.edge.pbx.view.summing.SummingInputLayout;

import com.edge.pbxdsp.R;
import com.hanlink.dsp.DspSettings;

import com.hanlink.dsp.ca.model.channel.SummingChannel;
import com.hanlink.dsp.protocols.DspProtocol;
import com.hanlink.dsp.util.DataUtil;
import com.hanlink.dsp.util.ViewUtil;
import com.qztech.bluetooth.event.NotifyDataReadEvent;
import com.qztech.sdk.ui.fragment.BaseFragment;
import com.qztech.utils.YzDebug;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//import butterknife.BindView;
//import butterknife.ButterKnife;
//import butterknife.Unbinder;

import static com.hanlink.dsp.DspSettings.SUMMING_SETTINGS;


public class Summing3Fragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener {
   // private Unbinder unbinder;
    public static final int CAR_TYPE_CAR  = 0;
    public static final int CAR_TYPE_MOTO = 1;
    public static final int CAR_TYPE_UTV  = 2;
    public static final int CAR_TYPE_REMOTE_DELAY  = 3;


    //@BindView(R.id.radioGroup)
    RadioGroup mRadioGroup;
    //@BindView(R.id.tvRead)
    TextView mTvRead;
    //@BindView(R.id.scrollView)
    ScrollView scrollView;

    //    @BindView(R.id.esv_eqchart)
//    EqView mEqChart;

    private RadioButton mRbAssing;
    private RadioButton mRb2CH;
    private RadioButton mRb4CH;
    private RadioButton mRbCustom;

    //@BindView(R.id.pbx_summing_remote_delay_layout)
    ViewGroup mRemoteDelayLayout;

    PbxImageButtonRadioLayout mPbxCarTypesLayout, mLeftRightDriverLayout;
    //@BindView(R.id.pbx_output_selects_layout)
    PbxOutputSelectChannelsLayout mPbxOutputSelectChannelsLayout;

    final List<PbxOutputSelectChannelView> mOutputViews = new ArrayList<>(8);
    SummingInputLayout mSummingInputLayout;

    private PbxCircleSeekBar mRemoteDelaySeekBar;

    protected int getResourceId() {
        return R.layout.fragement_summing2;
    }


    @Override
    public void onPause() {
        super.onPause();
        YzDebug.d("+++++++++++onPause+++++++++++++++");
        DataUtil.saveSummingSettingsToDb();
    }



    private void updateData() {
        ViewUtil.initOutputChannels(SUMMING_SETTINGS, mOutputViews);
        YzDebug.d("Yang","updateData-------------------:" + SUMMING_SETTINGS.getAssign()
        + " channel:"+ SUMMING_SETTINGS.getLastChannel());
        mRadioGroup.setOnCheckedChangeListener(null);
        if (SUMMING_SETTINGS.getAssign() == 1) {
            mRb2CH.setChecked(true);
            mSummingInputLayout.setClickable(false);
            mSummingInputLayout.setSelectChs(new int[]{1,1,0,0,0,0,0,0});
            mPbxOutputSelectChannelsLayout.setEnabled(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                for (PbxOutputSelectChannelView outputView : mOutputViews) {
                    outputView.setSelected(true);
                }
            }
        } else if (SUMMING_SETTINGS.getAssign() == 2) {
            mPbxOutputSelectChannelsLayout.setEnabled(false);
            mSummingInputLayout.setClickable(false);
            mSummingInputLayout.setSelectChs(new int[]{1,1,1,1,1,1,0,0});
            mRb4CH.setChecked(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                for (PbxOutputSelectChannelView outputView : mOutputViews) {
                    outputView.setSelected(true);
                }
            }

        } else {
            mPbxOutputSelectChannelsLayout.setEnabled(true);
            mSummingInputLayout.setClickable(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                int lastChannel = SUMMING_SETTINGS.getLastChannel();
                for (int i = 0, len = mOutputViews.size(); i < len; i++ ){
                    YzDebug.d("Yang" , " init data :"+i+" " + lastChannel);
                    mOutputViews.get(i).setSelected(i == lastChannel);
                }
            }
            mSummingInputLayout.setSelectChs(SUMMING_SETTINGS.getLastSummingChannel().getHigh_input_channels());
            mRbCustom.setChecked(true);
        }
        final SummingChannel channel = SUMMING_SETTINGS.getLastSummingChannel();
        if (channel != null){
            final int carType = SUMMING_SETTINGS.getCarType();
            mPbxCarTypesLayout.setSelectImageIndex(carType);
            mPbxOutputSelectChannelsLayout.setVisibility(carType == CAR_TYPE_REMOTE_DELAY?View.GONE:View.VISIBLE);
            mRemoteDelayLayout.setVisibility(carType == CAR_TYPE_REMOTE_DELAY?View.VISIBLE:View.GONE);
            mLeftRightDriverLayout.setSelectImageIndex(channel.getLowInputChannel(1));
            if (carType == CAR_TYPE_REMOTE_DELAY){
                mRemoteDelaySeekBar.setProgress(SUMMING_SETTINGS.getDelay());
            }
        }
        mPbxOutputSelectChannelsLayout.postInvalidate();
        mRadioGroup.setOnCheckedChangeListener(this);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mRadioGroup.setOnCheckedChangeListener(null);
        mRadioGroup = null;
      //  this.unbinder.unbind();
    }


    public void onRefreshFragment(int cmd) {
        if (cmd == CMD_SELECTED) {
            updateData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        ViewUtil.initChannelName(mOutputViews);
        ViewUtil.initCarType(mPbxOutputSelectChannelsLayout);

//        mRb2CH.setOnCheckedChangeListener(this);
//        mRb4CH.setOnCheckedChangeListener(this);
//        mRbCustom.setOnCheckedChangeListener(this);
        mRadioGroup.setOnCheckedChangeListener(this);
        updateData();

    }


    @Override
    public void onAttachFragment(@NonNull Fragment childFragment) {
        super.onAttachFragment(childFragment);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        YzDebug.d("PBX", "onCheckedChanged");
        if (!isChecked) return;
        switch (buttonView.getId()) {
            case R.id.rb_correlate:
                List<SummingChannel> summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(false);
                    channel.setHighInputChannel(i, true);
//                        mOutputList.get(i).setChecked(true);
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(1);
                updateData();
                break;
            case R.id.rb_2ch:
                summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(false);
                    switch (i) {
                        case 0:
                        case 2:
                            channel.setHighInputChannelNoSendCmd(0, true);
                            break;
                        case 1:
                        case 3:
                            channel.setHighInputChannelNoSendCmd(1, true);
                            break;
                        case 4:
                        case 5:
                            channel.setHighInputChannelNoSendCmd(0, true);
                            channel.setHighInputChannelNoSendCmd(1, true);
                            break;
                        case 6:
                        case 7:
                            break;
                    }
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(1);
                updateData();
                break;
            case R.id.rb_4ch:
                summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(false);
                    switch (i) {
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                            channel.setHighInputChannelNoSendCmd(i, true);
                            break;
                        case 4:
                        case 5:
                            channel.setHighInputChannelNoSendCmd(0, true);
                            channel.setHighInputChannelNoSendCmd(1, true);
                            channel.setHighInputChannelNoSendCmd(2, true);
                            channel.setHighInputChannelNoSendCmd(3, true);
                            break;
//                            case 5:
//                            case 7:
//                                channel.setHighInputChannelNoSendCmd(3, true);
//                                break;
                    }
//                        mOutputList.get(i).setChecked(true);
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(2);
                updateData();
                break;
            case R.id.rb_custom:
                summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(true);
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
//                        mOutputList.get(i).setChecked(false);
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(0);
                updateData();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        YzDebug.d("PBX", "onCheckedChanged22L:"+ checkedId +" "
        + R.id.rb_2ch +" " + R.id.rb_4ch +" " + R.id.rb_custom +" " + group.getCheckedRadioButtonId());
        switch (checkedId) {
            case R.id.rb_correlate:
                List<SummingChannel> summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(false);
                    channel.setHighInputChannel(i, true);
//                        mOutputList.get(i).setChecked(true);
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(1);
                updateData();
                break;
            case R.id.rb_2ch:
                summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(false);
                    switch (i) {
                        case 0:
                        case 2:
                        case 4:
                        case 6:
                            channel.setHighInputChannelNoSendCmd(0, true);
                            break;
                        case 1:
                        case 3:
                        case 5:
                        case 7:
                            channel.setHighInputChannelNoSendCmd(1, true);
                            break;
                    }
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(1);
                updateData();
                break;
            case R.id.rb_4ch:
                summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(false);
                    switch (i) {
                        case 0:
                        case 2:
                            channel.setHighInputChannelNoSendCmd(0, true);
                            break;
                        case 1:
                        case 3:
                            channel.setHighInputChannelNoSendCmd(1, true);
                            break;
                        case 4:
                            channel.setHighInputChannelNoSendCmd(2, true);
                            break;
                        case 5:
                            channel.setHighInputChannelNoSendCmd(3, true);
                            break;
                        case 6:
                            channel.setHighInputChannelNoSendCmd(4, true);
                            break;
                        case 7:
                            channel.setHighInputChannelNoSendCmd(5, true);
                            break;
                    }
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(2);
                updateData();
                break;
            case R.id.rb_custom:
                summingChannels = SUMMING_SETTINGS.getSummingChannels();
                for (int i = 0; i < summingChannels.size(); i++) {
                    SummingChannel channel = summingChannels.get(i);
                    channel.resetHighInputChannels(false);
                    if (!DspSettings.reset) {
                        channel.writeCmd(channel.getCmd(true));
                    }
//                        mOutputList.get(i).setChecked(false);
                }
                DspSettings.reset = false;
                SUMMING_SETTINGS.setAssign(0);
                updateData();
                break;
        }
    }

    @Override
    public void onViewCreated(View paramView, Bundle paramBundle) {
        super.onViewCreated(paramView, paramBundle);
       // this.unbinder = ButterKnife.bind(this, paramView);

        mRadioGroup = findViewById(R.id.radioGroup);
        mTvRead = findViewById(R.id.tvRead);
        scrollView = findViewById(R.id.scrollView);
        mRemoteDelayLayout = findViewById(R.id.pbx_summing_remote_delay_layout);
        mPbxOutputSelectChannelsLayout = findViewById(R.id.pbx_output_selects_layout);


        mRbAssing = paramView.findViewById(R.id.rb_correlate);
        mRb2CH = paramView.findViewById(R.id.rb_2ch);
        mRb4CH = paramView.findViewById(R.id.rb_4ch);
        mRbCustom = paramView.findViewById(R.id.rb_custom);
        mPbxCarTypesLayout = findViewById(R.id.pbx_output_select_cartypes_layout);
        mLeftRightDriverLayout = findViewById(R.id.pbx_summing_driver_layout);
        mLeftRightDriverLayout.setOnImageButtonRadioListener(mLeftRightDriverListener);
        mPbxCarTypesLayout.setOnImageButtonRadioListener(mCarTypesLayoutListener);
        ViewUtil.findOutputViews(mOutputViews,paramView, mChannelSelectListener);
        for (PbxOutputSelectChannelView outputView : mOutputViews) {
            outputView.setOnLongClickListener(mOutputViewLongClickListener);
        }

        mSummingInputLayout = findViewById(R.id.pbx_summing_input_select_layout);
        mSummingInputLayout.setOnInputLayoutListener(mOnInputLayoutListener);
        mRemoteDelaySeekBar = findViewById(R.id.pbx_summing_remote_delay_seekbar);
        final PbxCircleSeekBar.OnCircleSeekBarListener mOnCircleSeekBarListener = new PbxCircleSeekBar.OnCircleSeekBarListener() {
            private long mLastUpdate = 0;
            @Override
            public void onProgressChange(PbxCircleSeekBar seekBar, int progress, int action) {
                long time = SystemClock.elapsedRealtime();
                SUMMING_SETTINGS.setDelay(progress);
                if (action == MotionEvent.ACTION_UP || (time - mLastUpdate) > 300) {
                    DspProtocol.setDelay(progress);
                    mLastUpdate = time;
                }
            }
        };


        mRemoteDelaySeekBar.setOnCircleSeekBarFunListener((bar, id) -> {
            int value = 0;
            switch (id){
                case FUN_ID_ADD:
                    int p = mRemoteDelaySeekBar.getProgress();
                    if (p < 300){
                        value = p+1;
                    }
                    break;
                case FUN_ID_SUB:
                    p = mRemoteDelaySeekBar.getProgress();
                    if(p > 40){
                        value = p-1;
                    }
                    break;
            }
            if (value != 0){
                mRemoteDelaySeekBar.setProgress(value);
                mOnCircleSeekBarListener.onProgressChange(mRemoteDelaySeekBar,value, MotionEvent.ACTION_UP);

            }
        });
        mRemoteDelaySeekBar.setOnCircleSeekBarListener(mOnCircleSeekBarListener);


        mTvRead.setOnClickListener(v -> {
            mTvRead.setText("");
//            EventBus.getDefault().post(new NotifyDataReadEvent("3423423423423", 12));
        });
        TextView btnTest = paramView.findViewById(R.id.btnTest);
        btnTest.setOnClickListener(v -> scrollView.setVisibility(scrollView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE));

        if (true) {
            btnTest.setVisibility(View.VISIBLE);
            scrollView.setVisibility(View.VISIBLE);
        } else {
            btnTest.setVisibility(View.GONE);
            scrollView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(null);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(new Bundle());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRead(NotifyDataReadEvent event) {
        mTvRead.append(event.getLen() + " : " + event.getData() + "\n");
    }

    //===========================
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void setSelectChannelUI(int channel) {
        int index = 0;
        for (PbxOutputSelectChannelView outputView : mOutputViews) {
            outputView.setSelected(channel == index);
            index++;
        }
        mPbxOutputSelectChannelsLayout.postInvalidate();
    }

    private final SummingInputLayout.OnInputLayoutListener mOnInputLayoutListener = (index, isSelected) -> {
        int channel = SUMMING_SETTINGS.getLastChannel();
        SUMMING_SETTINGS.getLastSummingChannel().setHighInputChannel(index, isSelected);
        if (channel >= 0 && channel < mOutputViews.size()) {
            if (isSelected) {
                mOutputViews.get(channel).addSum(index);
            } else {
                mOutputViews.get(channel).removeSum(index);
            }

        }
    };
    private final View.OnLongClickListener mOutputViewLongClickListener = v -> {
        if ( v instanceof PbxOutputSelectChannelView){
            final PbxOutputSelectChannelView cv = (PbxOutputSelectChannelView) v;
            ViewUtil.showChangeChannelNameDialog(getContext(),cv.getChannelIndex(), name->cv.setName(name));
            return true;
        }
        return false;
    };
    private final PbxOutputSelectChannelView.OnCheckChangeListener mChannelSelectListener = new PbxOutputSelectChannelView.OnCheckChangeListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onCheckChange(PbxOutputSelectChannelView view, boolean isChecked) {
            for (PbxOutputSelectChannelView outputView : mOutputViews) {
                if (outputView.getId() != view.getId()) {
                    outputView.setSelected(false);
                }
            }
            SUMMING_SETTINGS.setLastChannel(view.getChannelIndex());
            mSummingInputLayout.setSelectChs(SUMMING_SETTINGS.getLastSummingChannel().getHigh_input_channels());
            mPbxOutputSelectChannelsLayout.postInvalidate();
        }
    };

    //
    private final PbxImageButtonRadioLayout.OnImageButtonRadioListener mCarTypesLayoutListener = new PbxImageButtonRadioLayout.OnImageButtonRadioListener() {
        @Override
        public void onChecked(ImageButton view) {
            mLeftRightDriverLayout.setVisibility(view.getId() == R.id.pbx_summing_btn_car ? View.VISIBLE : View.INVISIBLE);
            if (view.getId() == R.id.pbx_summing_btn_remote_delay){
                mRemoteDelayLayout.setVisibility(View.VISIBLE);
                mPbxOutputSelectChannelsLayout.setVisibility(View.GONE);
            }else {
                mRemoteDelayLayout.setVisibility(View.GONE);
                mPbxOutputSelectChannelsLayout.setVisibility(View.VISIBLE);
            }
            switch (view.getId()) {
                case R.id.pbx_summing_btn_car:
                    SUMMING_SETTINGS.setCarType(CAR_TYPE_CAR);
                    int driver = SUMMING_SETTINGS.getDriverType();
                    mPbxOutputSelectChannelsLayout.setCarTypeDrawable(driver == 0?R.drawable.pbx_output_select_car_left:R.drawable.pbx_output_select_car_right);
                    mLeftRightDriverLayout.setSelectImageIndex(driver);
                    break;
                case R.id.pbx_summing_btn_motorcycle:
                    SUMMING_SETTINGS.setCarType(CAR_TYPE_MOTO);
                    mPbxOutputSelectChannelsLayout.setCarTypeDrawable(R.drawable.pbx_output_select_moto);
                    break;
                case R.id.pbx_summing_btn_utv:
                    SUMMING_SETTINGS.setCarType(CAR_TYPE_UTV);
                    mPbxOutputSelectChannelsLayout.setCarTypeDrawable(R.drawable.pbx_output_select_utv);
                    break;
                case R.id.pbx_summing_btn_remote_delay:
                    SUMMING_SETTINGS.setCarType(CAR_TYPE_REMOTE_DELAY);
//                    mRemoteDelaySeekBar.setProgressForce(DspSettings.SUMMING_SETTINGS.getDelay());
                    mRemoteDelaySeekBar.setProgressForce(SUMMING_SETTINGS.getDelay());
                    break;
            }
        }
    };
    private final PbxImageButtonRadioLayout.OnImageButtonRadioListener mLeftRightDriverListener = new PbxImageButtonRadioLayout.OnImageButtonRadioListener() {
        @Override
        public void onChecked(ImageButton view) {
            switch (view.getId()) {
                case R.id.pbx_summing_btn_left_driver:
                    SUMMING_SETTINGS.setDriverType(0);
                    mPbxOutputSelectChannelsLayout.setCarTypeDrawable(R.drawable.pbx_output_select_car_left);
                    break;
                case R.id.pbx_summing_btn_right_driver:
                    SUMMING_SETTINGS.setDriverType(1);
                    mPbxOutputSelectChannelsLayout.setCarTypeDrawable(R.drawable.pbx_output_select_car_right);
                    break;
            }
        }
    };
}
